package com.kaiwukj.android.ufamily.mvp.http.callback;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.NetworkUtils;
import com.kaiwukj.android.mcas.mvp.IView;

import java.net.ConnectException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;

/**
 * 统一的网络callback
 *
 * @param <T>
 * @author huiwings
 * @date 2019-10-29 11:44
 */
public abstract class ApiCallBack<T> implements Observer<T> {

    private IView mView;
    private int taskId = -1;

    public ApiCallBack() {
    }

    public ApiCallBack(IView iView) {
        mView = iView;
    }

    public ApiCallBack(IView iView, int taskId) {
        mView = iView;
        this.taskId = taskId;
    }

    public ApiCallBack(RxErrorHandler rxErrorHandler) {
        /*super(rxErrorHandler);*/
    }

    public ApiCallBack(RxErrorHandler rxErrorHandler, IView iView) {
        //  super(rxErrorHandler);
        mView = iView;
    }

    public ApiCallBack(RxErrorHandler rxErrorHandler, IView iView, int taskId) {
        // super(rxErrorHandler);
        mView = iView;
        this.taskId = taskId;
    }


   /* @Override
    protected void onStart() {
        super.onStart();
        if(!NetworkUtils.isConnected()){
            onError(new ConnectException("网络异常，请检查网络连接!"));
        }
    }*/

    @Override
    public void onSubscribe(Disposable d) {
        if (!NetworkUtils.isConnected()) {
            onError(new ConnectException("网络异常，请检查网络连接!"));
        }
    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
        if (mView != null) {
            mView.onTaskSuccess(taskId);
        }
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onError(Throwable e) {
        onFailure(e);
        if (mView != null) {
            mView.hideLoading();
        }
    }

    public abstract void onSuccess(@NonNull T result);

    /**
     * 完成请求(包括异常情况)
     * 多Task请覆盖 并指定taskId
     */
    public void onFailure(@NonNull Throwable e) {
        if (mView != null) {
            mView.showMessage(ApiExceptionHelper.handleException(e));
            mView.onTaskErr(taskId);
        }
    }


}
